package org.nextive.android.weightapp.utils;

import java.util.ArrayList;

import org.nextive.android.weightapp.entities.AccountData;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription;
import android.accounts.OnAccountsUpdateListener;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;

public class AccountsHelper extends Activity implements OnAccountsUpdateListener 
{
	private ArrayList<AccountData> accounts;
	private AccountAdapter accountAdapter;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
		accounts = new ArrayList<AccountData>();
		accountAdapter = new AccountAdapter(this, getLayoutInflater(),accounts);
		AccountManager.get(this).addOnAccountsUpdatedListener(this, null, true);
    }
	
	private static AuthenticatorDescription getAuthenticatorDescription(String type, AuthenticatorDescription[] dictionary) 
	{
        for (int i = 0; i < dictionary.length; i++) 
        {
            if (dictionary[i].type.equals(type)) 
            {
                return dictionary[i];
            }
        }
        throw new RuntimeException("Unable to find matching authenticator");
    }
	
	@Override
	public void onAccountsUpdated(Account[] a) 
	{
		accounts.clear();
        AuthenticatorDescription[] accountTypes = AccountManager.get(this).getAuthenticatorTypes();

        for (int i = 0; i < a.length; i++) 
        {
            String systemAccountType = a[i].type;
            AuthenticatorDescription ad = getAuthenticatorDescription(systemAccountType, accountTypes);
            PackageManager packageManager = getPackageManager();
            AccountData data = new AccountData(a[i].name, ad, packageManager);
            accounts.add(data);
        }
        accountAdapter.notifyDataSetChanged();
	}
	
	public ArrayList<AccountData> getAccounts() 
	{
		return accounts;
	}

	public AccountAdapter getAccountAdapter() 
	{
		return accountAdapter;
	}

	@Override
	protected void onDestroy() 
	{
		AccountManager.get(this).removeOnAccountsUpdatedListener(this);
		super.onDestroy();
	}
}
